/**
 * 
 */
package edu.umd.clip.lm.util;

import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;


public class CountDistributionBinding extends TupleBinding<CountDistribution> {
	public static final CountDistributionBinding instance = new CountDistributionBinding();
	
	private CountDistributionBinding() {}
	
	/* (non-Javadoc)
	 * @see com.sleepycat.bind.tuple.TupleBinding#entryToObject(com.sleepycat.bind.tuple.TupleInput)
	 */
	@Override
	public CountDistribution entryToObject(TupleInput input) {
		long totalCount = input.readPackedLong();
		
		int numCounts = input.readPackedInt();
		Long2IntMap counts = new Long2IntMap(numCounts);
		for(int i=0; i<numCounts; ++i) {
			long k = input.readPackedLong();
			int v = input.readPackedInt();
			counts.put(k, v);
		}
		return new CountDistribution(counts, totalCount);
	}

	/* (non-Javadoc)
	 * @see com.sleepycat.bind.tuple.TupleBinding#objectToEntry(java.lang.Object, com.sleepycat.bind.tuple.TupleOutput)
	 */
	@Override
	public void objectToEntry(CountDistribution dist, TupleOutput output) {
		output.writePackedLong(dist.getTotalCount());
		output.writePackedInt(dist.getCounts().size());
		for(Long2IntMap.Iterator i = dist.getCounts().iterator(); i.hasNext(); ) {
			Long2IntMap.Entry e = i.next();
			output.writePackedLong(e.getKey());
			output.writePackedInt(e.getValue());
		}
	}
	
}